package cn.edu.cug.cs.gtl.apis.ui.catalogtree;


import cn.edu.cug.cs.gtl.apis.ui.AbstractApplication;
import cn.edu.cug.cs.gtl.apis.ui.tree.Tree;
import cn.edu.cug.cs.gtl.apis.ui.tree.TreeMouseListener;
import cn.edu.cug.cs.gtl.protos.DataCatalog;
import cn.edu.cug.cs.gtl.protos.DataGroup;
import cn.edu.cug.cs.gtl.protos.DataItem;

import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.event.MouseEvent;

public class CatalogTreeMouseListener extends TreeMouseListener {
    public CatalogTreeMouseListener(Tree theTree, AbstractApplication theApp) {
        super(theTree, theApp);
    }

    /**
     * {@inheritDoc}
     *
     * @param e
     */
    @Override
    public void mouseReleased(MouseEvent e) {
        super.mouseReleased(e);
        if (SwingUtilities.isRightMouseButton(e)) {
            int selRow = theTree.getRowForLocation(e.getX(), e.getY());
            TreePath selPath = theTree.getPathForLocation(e.getX(), e.getY());
            theTree.setSelectionPath(selPath);
            if (selRow > -1) {
                theTree.setSelectionRow(selRow);
            } else {
                theTree.setSelectionRow(0);
            }
            Object obj = theTree.getCurrentReferencedObject();
            if (obj == null)
                return;
            if (obj instanceof DataCatalog) {
                JPopupMenu popupMenu = CatalogTree.createDefaultPopupMenuForCatalogNode();
                ((CatalogTree) theTree).setCatalogNodePopupMenu(popupMenu);
                popupMenu.show(e.getComponent(), e.getX(), e.getY());
            } else if (obj instanceof DataGroup) {
                JPopupMenu popupMenu = CatalogTree.createDefaultPopupMenuForGroupNode();
                ((CatalogTree) theTree).setGroupNodePopupMenu(popupMenu);
                popupMenu.show(e.getComponent(), e.getX(), e.getY());
            } else if (obj instanceof DataItem) {
                JPopupMenu popupMenu = CatalogTree.createDefaultPopupMenuForItemNode();
                ((CatalogTree) theTree).setItemNodePopupMenu(popupMenu);
                popupMenu.show(e.getComponent(), e.getX(), e.getY());
            } else {
                JPopupMenu popupMenu = CatalogTree.createDefaultPopupMenuForTree();
                ((CatalogTree) theTree).setTreePopupMenu(popupMenu);
                popupMenu.show(e.getComponent(), e.getX(), e.getY());
            }
        }
    }
}
